<template>
  <div class="app-container">
    <div class="page-card top-tabs">
      <el-tabs v-model="queryParams.examSubjectId" @tab-click="getList">
        <el-tab-pane
          v-for="item in tabList"
          :key="item.id"
          :label="item.name"
          :name="item.id.toString()"
        ></el-tab-pane>
      </el-tabs>
    </div>

    <div class="page-card m-top">
      <div class="page-form">
        <el-select
          v-if="$auth.hasRole('admin')"
          v-model="queryParams.examSchoolId"
          placeholder="全部学校"
          clearable
          @change="handleSearch"
        >
          <el-option
            v-for="dict in xxlb"
            :key="dict.id"
            :label="dict.schoolName"
            :value="dict.id"
          />
        </el-select>
        <!-- <el-select
          v-model="queryParams.uploadStatus"
          placeholder="上传状态"
          clearable
          @change="handleSearch"
        >
        </el-select> -->
      </div>
      <div class="sm-status-box">
        <span> 扫描状态：</span><span>{{ scanStatusName || "未开启" }}</span>
        <div class="progress-box">
          <div class="progress" :style="'width:' + uploadProgress + '%'"></div>
        </div>
        <span>{{ uploadProgress }}%</span>
        <!-- <span class="rs">0/1000</span>
        <span>现在人数：0/100</span> -->
      </div>

      <el-table
        stripe
        border
        ref="tableList"
        v-loading="loading"
        :data="tableData"
        style="width: 100%; margin-top: 20px"
        row-key="id"
      >
        <el-table-column label="序号" type="index" align="center">
        </el-table-column>
        <el-table-column
          label="参考学校"
          align="center"
          prop="schoolName"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="上报人数"
          align="center"
          prop="reportedNumber"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="已上传人数"
          align="center"
          prop="uploadedNumber"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="客户端上传人数"
          align="center"
          prop="clientUploadeNumber"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="已扫描张数"
          align="center"
          prop="scannedNumber"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="上传进度"
          align="center"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="scope">
            {{ scope.row.uploadProgress }}%
          </template>
        </el-table-column>
        <el-table-column
          label="缺考人数"
          align="center"
          prop="missingExamNumber"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="未上传人数"
          align="center"
          class-name="color-danger"
          prop="notUploadedNumber"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="考号异常"
          align="center"
          class-name="color-danger"
          prop="examNumberAbnormal"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="选项异常"
          align="center"
          class-name="color-danger"
          prop="optionAbnormal"
          :show-overflow-tooltip="true"
        />
        <!-- <el-table-column
          label="上传状态"
          align="center"
          prop=""
          :show-overflow-tooltip="true"
        /> -->

        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-link type="primary" @click="xq(scope.row)">查看详情</el-link>
          </template></el-table-column
        ></el-table
      >

      <div class="page-bottom">
        <div class="sel-box">
          <p>共 {{ tableData.length }} 项</p>

          <template v-if="$auth.hasRole('admin')">
            <el-button
              type="primary"
              @click="bgsmzt"
              :disabled="tableData.length == 0"
              >变更扫描状态</el-button
            >
            <el-button
              type="primary"
              @click="xq(false)"
              :disabled="tableData.length == 0"
              >查看全部</el-button
            >
            <el-button
              type="primary"
              :loading="exportLoading"
              @click="exportAllProgress"
              >{{ exportLoading ? "导出中..." : "导出全部进度" }}</el-button
            >
          </template>
        </div>
        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </div>
    </div>

    <el-dialog
      ref="editDialog"
      class="editKmVisible"
      title="变更扫描状态"
      :visible.sync="editKmVisible"
      width="436px"
      :before-close="beforeClose"
    >
      <el-form
        ref="editForm"
        :model="editForm"
        :rules="rules"
        label-position="left"
        label-width="140px"
      >
        <el-form-item label="选择扫描状态" prop="scanStatus">
          <el-select v-model="editForm.scanStatus">
            <el-option label="开启扫描" value="1"></el-option>
            <el-option label="暂停扫描" value="2"></el-option>
            <el-option label="结束扫描" value="3"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span class="danger">{{ editMsg }}</span>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose">返 回</el-button>
        <el-button type="primary" @click="editSubmit" :loading="loading"
          >保 存</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { debounce } from "lodash";
import {
  scanExamSubject,
  scanStatisticsHomepage,
  scanOnoff,
  scanStatisticsGetTitle,
  exportsmgl
} from "@/api/xmgl/smgl";
import { scanQuestionCardSchoolListSchool } from "@/api/xmgl/tkcx";
export default {
  name: "Project_smgl",
  data() {
    return {
      firstLoad: true,

      loading: false,
      xmxx: {},

      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 15,
        examSchoolId: "",
        examSubjectId: "",
      },
      activeName: "",

      xxlb: [],

      tabList: [],

      tableData: [],
      uploadProgress: "",
      scanStatusName: "",

      editKmVisible: false,
      editForm: {
        scanStatus: "",
      },
      rules: {
        scanStatus: [
          { required: true, message: "扫描状态不能为空", trigger: "change" },
        ],
      },

      editMsg: "",
      exportLoading: false,
    };
  },
  created() {
    this.loading = true;
    this.$store.dispatch("getXmxx").then((res) => {
      this.xmxx = res;

      if (
        this.$auth.hasRole("admin") ||
        this.$auth.hasExamPermi("reviewing:teachers:xxscjd")
      ) {
        scanExamSubject({ examId: this.xmxx.id }).then((res) => {
          this.tabList = res.data;
          this.queryParams.examSubjectId = res.data[0].id.toString();
          this.scanQuestionCardSchoolListSchool();
        });
      } else if (this.$auth.hasExamPermi("reviewing:teachers:xxscjdkm")) {
        this.tabList = this.$store.state.xmgl.examSubjects.map((item) => {
          return {
            ...item,
            id: item.examSubjectId,
            name: item.examSubjectName,
          };
        });
        this.queryParams.examSubjectId = this.tabList[0].id.toString();
        this.scanQuestionCardSchoolListSchool();
      }
    });
  },
  activated() {
    if (!this.firstLoad) {
      this.getList();
    }
    this.firstLoad = false;
  },
  methods: {
    async exportAllProgress() {
      this.exportLoading = true;
      try {
        const res = await exportsmgl({examId:this.xmxx.id});
        // 创建临时链接
        const blob = new Blob([res.data]);
        if (blob.size == 0) {
          this.$modal.alert("当前暂无数据，无法导出");
          return;
        }
        const downloadUrl = window.URL.createObjectURL(blob);
        const fileName = `扫描进度_${new Date().getTime()}.xlsx`;
        // 创建隐藏的a标签触发下载
        const link = document.createElement("a");
        link.href = downloadUrl;
        link.download = fileName;
        link.style.display = "none";
        document.body.appendChild(link);
        link.click();
        // 清理资源
        window.URL.revokeObjectURL(downloadUrl);
        document.body.removeChild(link);
        this.$message.success("文件下载成功");
        this.exportLoading = false;
      } catch (error) {
        console.log(error, "error");
        this.$message.error("文件下载失败");
        this.exportLoading = false;
        return false;
      }
    },
    scanQuestionCardSchoolListSchool() {
      scanQuestionCardSchoolListSchool({ examId: this.xmxx.id }).then((res) => {
        this.xxlb = res.rows;

        if (!this.$auth.hasRole("admin")) {
          this.queryParams.examSchoolId = this.xxlb.filter((item) => {
            return this.$store.state.user.deptId == item.schoolId;
          })[0].id;
        }

        this.getList();
      });
    },
    getList() {
      this.loading = true;
      this.tableData = [];
      scanStatisticsHomepage({ ...this.queryParams, examId: this.xmxx.id })
        .then((response) => {
          this.total = response.data.pageList.total;
          this.tableData = response.data.pageList.records;
          this.uploadProgress = response.data.uploadProgress;
          this.scanStatusName = response.data.scanStatusName;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    debouncedSearch: debounce(function () {
      this.queryParams.pageNum = 1;
      this.getList();
    }, 500),
    handleSearch() {
      this.debouncedSearch();
    },
    xq(row) {
      this.$store.dispatch("app/setIsRefresh", true).then((res) => {
        if (row) {
          this.$router.push({
            path: "/kwgl/smgl-data/index",
            query: {
              examSchoolId: row.examSchoolId,
              schoolName: row.schoolName,
              examSubjectId: this.queryParams.examSubjectId,
            },
          });
        } else {
          this.$router.push({
            path: "/kwgl/smgl-data/index",
            query: {
              examSubjectId: this.queryParams.examSubjectId,
            },
          });
        }
      });
    },
    beforeClose(done) {
      this.editForm = {
        scanStatus: "",
      };
      this.$nextTick(() => {
        this.$refs.editForm.clearValidate();
        done();
      });
    },
    handleClose() {
      this.beforeClose(() => {
        this.editKmVisible = false;
      });
    },
    editSubmit() {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          scanOnoff({
            scanStatus: this.editForm.scanStatus,
            examId: this.xmxx.id,
            examSubjectId: this.queryParams.examSubjectId,
          }).then((res) => {
            this.$modal.msgSuccess("操作成功");
            this.handleClose();
            this.getList();
          });
        }
      });
    },
    bgsmzt() {
      this.loading = true;
      scanStatisticsGetTitle({
        examId: this.xmxx.id,
        examSubjectId: this.queryParams.examSubjectId,
      })
        .then((res) => {
          this.editMsg = res.msg;
          this.editKmVisible = true;
        })
        .finally(() => {
          this.loading = false;
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.editKmVisible {
  .el-input,
  .el-cascader,
  .el-select {
    width: 240px;
  }
}
.sm-status-box {
  width: 774px;
  height: 34px;
  line-height: 34px;
  border: 1px solid #dee1e7;
  border-radius: 4px;
  font-size: 14px;
  padding: 0 14px;
  color: #8e96a4;
  display: flex;
  align-items: center;

  .progress-box {
    width: 100px;
    height: 10px;
    background: #eff1f4;
    border-radius: 5px;
    margin: 0 10px;

    .progress {
      background: #1b48db;
      border-radius: 5px;
      height: 10px;
    }
  }

  .rs {
    margin: 0 10px;
  }
}

.danger {
  color: #ec555a;
}
</style>